//
//  WLButtonCountdownManager.m
//  WLButtonCountingDownDemo
//
//  Created by wayne on 16/1/14.
//  Copyright © 2016年 ZHWAYNE. All rights reserved.
//

#import "WLButtonCountdownManager.h"
#import <UIKit/UIKit.h>

@interface WLCountdownTask : NSOperation

/**
 *  计时中回调
 */
@property (copy, nonatomic) void (^countingDownBlcok)(NSTimeInterval timeInterval);
/**
 *  计时结束后回调
 */
@property (copy, nonatomic) void (^finishedBlcok)(NSTimeInterval timeInterval);
/**
 *  计时剩余时间
 */
@property (assign, nonatomic) NSTimeInterval leftTimeInterval;
/**
 *  后台任务标识，确保程序进入后台依然能够计时
 */
@property (assign, nonatomic) UIBackgroundTaskIdentifier taskIdentifier;

/**
 *  `NSOperation`的`name`属性只在iOS8+中存在，这里定义一个属性，用来兼容 iOS7
 */
@property (copy, nonatomic) NSString *operationName;

@property (nonatomic, assign) BOOL stop;



@end


@implementation WLCountdownTask

- (void)dealloc {
    _countingDownBlcok = nil;
    _finishedBlcok     = nil;
}

- (void)main {
    
    NSLog(@"mian");
    self.taskIdentifier = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    self.stop = NO;
    while (--_leftTimeInterval > 0) {
        
        if (self.stop) {
            
            NSLog(@"任务已经停止");
            
            break;
        }
        NSLog(@"任务还剩下%.0f",_leftTimeInterval);
        [NSThread sleepForTimeInterval:1];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (_finishedBlcok) {
            NSLog(@"任务结束的block");
            _finishedBlcok(_leftTimeInterval);
        }
    });
    
    if (self.taskIdentifier != UIBackgroundTaskInvalid) {
        [[UIApplication sharedApplication] endBackgroundTask:self.taskIdentifier];
        self.taskIdentifier = UIBackgroundTaskInvalid;
    }
}


@end



@interface WLButtonCountdownManager ()

@property (nonatomic, strong)WLCountdownTask *runingTask;

@end

@implementation WLButtonCountdownManager

+ (instancetype)defaultManager {
    static id instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self _alloc] _init];
    });
    
    if ([instance class] != [WLButtonCountdownManager class]) {
        NSCAssert(NO, @"该类不允许被继承");
    }
    
    return instance;
}

+ (instancetype)alloc {
    NSCAssert(NO, @"请使用`+defaultManager`方法获取实例");
    return nil;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    NSCAssert(NO, @"请使用`+defaultManager`方法获取实例");
    return nil;
}

+ (instancetype)_alloc {
    return [super allocWithZone:NSDefaultMallocZone()];
}

- (instancetype)init {
    NSCAssert(NO, @"请使用`+defaultManager`方法获取实例");
    return nil;
}

- (instancetype)_init {
    if (self = [super init]) {
        _pool = [[NSOperationQueue alloc] init];
    }
    
    return self;
}


- (void)startCounDown:(NSTimeInterval)count finished:(void (^)(NSTimeInterval))finished{
    
    if (_pool.operations.count > 0) {
        
        finished(0);
        
        return;
    }
    self.runingTask = [[WLCountdownTask alloc] init];
    self.runingTask.stop = NO;
    self.runingTask.finishedBlcok = finished;
    self.runingTask.leftTimeInterval = count;
    [_pool addOperation:self.runingTask];
    
}

- (void)stopTask{
    
    if (self.runingTask.stop) {
        
        return;
    }
    
    self.runingTask.stop = YES;
    
}

- (BOOL)stop{
    
    return self.runingTask.stop || self.runingTask.cancelled;
}

@end
